package com.doeis.jpush;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.device.AliasDeviceListResult;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

import com.doeis.common.utils.StringUtils;
import com.doeis.log.QueueManager;
import com.doeis.minaserver.NettyServer;
import com.doeis.minaserver.SystemProperties;
import com.doeis.push.BaiduServiceContext;
import com.doeis.push.PushBaidu;
import com.doeis.uwork.entity.mongo.MinaPushLog;
import com.voland.core.utils.DateUtils;
import com.voland.core.utils.IDGenerator;

public class DoeisJPush {

	protected static final Logger LOG = LoggerFactory
			.getLogger(DoeisJPush.class);
	
	/**
	 * 方法介绍  发送极光推送消息, alias为标示, 单个用户发送
	 * @param userid
	 * @param context
	 * @author tianbx
	 * @version 2016年5月21日下午4:25:31
	 */
	public static void sendNotification(String userid, String context) {
		MinaPushLog pushLog = new MinaPushLog();
		try{
			pushLog.setId(IDGenerator.uuid());
			pushLog.setStatus(false);
			pushLog.setUser_id(userid);
			pushLog.setContent(context);
			pushLog.setCreateTime(DateUtils.currentDateTime());
			PushBaidu pushBaidu = BaiduServiceContext.getPlanBaidu(userid);
			if (pushBaidu == null) {
				return;
			}

			String beQuiet = pushBaidu.getQuiet();
			if(beQuiet==null){
				beQuiet = "1";
			}
			
			if (StringUtils.isBlank(context)) {
				context = "";
			}

			if (context.length() > 50) {
				context = context.substring(0, 50);
			}

			Integer count = pushBaidu.getCount();
			if (count == null) {
				count = 0;
			}
			count += 1;
			pushBaidu.setCount(count);

			JPushClient jpushClient = null ;

			// For push, all you need do is to build PushPayload object.
			PushPayload payload =  null;
			if( pushBaidu.getDevice_type() ==3  ){//android
				jpushClient =  new JPushClient(
						SystemProperties.getPushSecretKeyAndroid(),
						SystemProperties.getPushApiKeyAndroid(), 3);
				payload = buildPushObject_android_alias(userid, context, count);
				
			}else if( pushBaidu.getDevice_type() ==4 ){//ios
				if(pushBaidu.getAppstore()!=null && pushBaidu.getAppstore()){
					jpushClient = new JPushClient(
							SystemProperties.getPushSecretKeyAppstore(),
							SystemProperties.getPushApiKeyAppstore(), 3);
					payload = buildPushObject_ios_alias(userid, context,
							beQuiet, count);
					
				}else{
					jpushClient =  new JPushClient(
							SystemProperties.getPushSecretKey(),
							SystemProperties.getPushApiKey(), 3);
					payload = buildPushObject_ios_alias(userid, context,
							beQuiet, count);
				}
			}
			
			if(payload == null){
				return ;
			}
			
			try {
				PushResult result = jpushClient.sendPush(payload);
				pushLog.setSendResult(result.getOriginalContent());
				pushLog.setStatus(true);
//				LOG.info("Got JPush result - " + result.getOriginalContent());

			} catch (APIConnectionException e) {
				LOG.error("Connection error. Should retry later. ", e);
				pushLog.setSendResult("Connection error. Should retry later. "+e.getMessage());
			} catch (APIRequestException e) {
				LOG.error(
						"Error response from JPush server. Should review and fix it. ",
						e);
				LOG.info("HTTP Status: " + e.getStatus());
				LOG.info("Error Code: " + e.getErrorCode());
				LOG.info("Error Message: " + e.getErrorMessage());
				LOG.info("Msg ID: " + e.getMsgId());
				pushLog.setSendResult(e.getErrorMessage());
			}
		}catch(Exception e){
			LOG.info("发送信息错误: {"+userid+ "}" + e.getMessage());
			pushLog.setSendResult("发送信息错误: " + e.getMessage());
		}finally{
			QueueManager queueManager = NettyServer.getInstance().getT(QueueManager.class);
			if(queueManager!=null){
				queueManager.sendLog(pushLog);
			}
		}
	}
	
	/**
	 * 方法介绍  android设备用户alias为标示, 单个用户
	 * @param userid
	 * @param alert
	 * @param count
	 * @return
	 * @author tianbx
	 * @version 2016年5月21日下午4:23:12
	 */
	 public static PushPayload buildPushObject_android_alias(String userid, String alert, int count) {
	        return PushPayload.newBuilder()
	                .setPlatform(Platform.android())
	                .setAudience(Audience.alias(userid))
	                .setNotification(Notification.newBuilder()
	                		.setAlert(alert)
	                		.addPlatformNotification(AndroidNotification.newBuilder()
	                				.setTitle("你有新的消息").build())
	                		.addPlatformNotification(IosNotification.newBuilder()
	                				.setBadge(count)
	                				.build())
	                		.build())
	                .build();
	    }

	/**
	 * 方法介绍   ios设备用户alias为标示, 单个用户
	 * @param userid
	 * @param context
	 * @param beQuiet
	 * @param count
	 * @return
	 * @author tianbx
	 * @version 2016年5月21日下午4:24:13
	 */
	public static PushPayload buildPushObject_ios_alias(String userid,
			String context, String beQuiet, int count  ) {
		Options apnsProduction = null;
		if(2 == SystemProperties.getPushDeployStatus()){
			apnsProduction = Options.newBuilder()
			        .setApnsProduction(true)
			        .build();
		}else{
			apnsProduction = Options.newBuilder()
			        .setApnsProduction(false)
			        .build();
		}
		
		
		if ("1".equals(beQuiet)) {
			 return PushPayload.newBuilder()
		                .setPlatform(Platform.all())
		                .setAudience(Audience.alias(userid))
		                .setOptions(apnsProduction)
		                .setNotification(Notification
								.newBuilder()
								.addPlatformNotification(
										IosNotification.newBuilder()
//												.incrBadge(1)
												.setAlert(context)
												.setBadge(count)
												.setSound("sound.caf")
												.addExtra("from", "JPush")
												.build()).build())
		                .build();
			
		} else {
			
			 return PushPayload.newBuilder()
		                .setPlatform(Platform.all())
		                .setOptions(apnsProduction)
		                .setAudience(Audience.alias(userid))
		                .setNotification(Notification
								.newBuilder()
								.addPlatformNotification(
										IosNotification.newBuilder()
												.setAlert(context)
//												.incrBadge(1)
												.setBadge(count)
//												.setSound("")
												.disableSound()
//												.setSound(null)
												.addExtra("from", "JPush")
												.build()).build())
		                .build();
		}
	}
	
	
	/**
	 * f5cfd1e652e7f9e90152e8c99d494400  罗美群 android [02064093fd8, 0504712300c]
	 * 方法介绍  清楚一个别名绑定多个手机的问题
	 * @throws APIConnectionException
	 * @throws APIRequestException
	 * @author tianbx
	 * @version 2016年5月23日下午4:27:44
	 */
	public static void updateAlias(String alias, String registrationId, Integer device_type) throws APIConnectionException, APIRequestException{
		if(alias==null){
			return ;
		}
		
		if(registrationId==null){
			return ;
		}
		
		if(device_type==null){
			return ;
		}
		
		JPushClient	jpushClient =  new JPushClient(
					SystemProperties.getPushSecretKey(),
					SystemProperties.getPushApiKey(), 3);		
		
		AliasDeviceListResult listResult  = jpushClient.getAliasDeviceList(alias, "android");
		if(listResult.registration_ids!=null && listResult.registration_ids.size() >0 ){
			if(listResult.registration_ids.contains(registrationId)){
				if(listResult.registration_ids.size()>1){
					jpushClient.deleteAlias(alias, "android");
					jpushClient.updateDeviceTagAlias(registrationId, alias, null, null);
				}
			}else{
				jpushClient.deleteAlias(alias, "android");
				if(device_type==3){//android
					jpushClient.updateDeviceTagAlias(registrationId, alias, null, null);
				}
			}
		}
		
		listResult  = jpushClient.getAliasDeviceList(alias, "ios");
		if(listResult.registration_ids!=null && listResult.registration_ids.size() >0 ){
			if(listResult.registration_ids.contains(registrationId)){
				if(listResult.registration_ids.size()>1){
					jpushClient.deleteAlias(alias, "ios");
					jpushClient.updateDeviceTagAlias(registrationId, alias, null, null);
				}
			}else{
				jpushClient.deleteAlias(alias, "ios");
				if(device_type==4){//ios
					jpushClient.updateDeviceTagAlias(registrationId, alias, null, null);
				}
			}
		}
	}
	
	
}
